# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "真实惠百万医疗险"

    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(0, 56)],
            # 有无社保
            "socialSec": ["Y", "N"],
            # 交费方式
            "payType": ["年交", "月交"],
            # 保障期限
            "expire": ["1年"],
            # 一般医疗保险金
            "generalMedical": ["1000000"],
            # 重大医疗保险金
            "seriousMedical": ["4000000"]
        }
        for v in product(plan["year"], plan["socialSec"], plan["payType"], plan["expire"], plan["generalMedical"],
                         plan["seriousMedical"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):
        data = {"productCode": "1336", "productName": "有社保" if dt["socialSec"] == "Y" else "无社保", "salePlanCode": "GHGW_1007", "sex": "0",
                "birthDate": ""+str(2020-int(dt["year"]))+"-01-01", "insurePeriod": "1Y", "type": "web", "system": "gh"}
        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "成功" in r.text :
            price = r.json()["content"]["resultPrice"]
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price if dt["payType"] == "年交" else Helper.decimalParse(float(r.json()["content"]["resultPrice"]) * 0.09)
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*产品信息更新失败:%d*/"%dt["id"])
